/*
 * @Author       : Li Ming Yang
 * @Date         : 2023-08-08 09:29:21
 * @Description  : 存放缓存数据
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2024-03-22 16:31:02
 */

// 本地存储缓存名称，此处出现的缓存名称再执行setState时会自动存储到本地缓存中，执行initApp时会自动读取本地缓存
export const cacheNames = ["isAgreest", "review-edit", "ad-popup-op", "refundAgreementConfig", "time-out", "payStatus", "couponUnUseList", "couponBindTips", "cardBindTips"]

export default {
  state: {},
  getters: {},
  mutations: {
    // 初始化缓存
    INIT_CACHE(state) {
      // 初始化本地缓存
      cacheNames.forEach((name) => {
        let data = uni.getStorageSync(name)
        if (data) state[name] = data
      })
    },
    // 设置缓存
    SET_CACHE(state, data) {
      // 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
      let nameArr = data.name.split(".")
      let name = ""
      let len = nameArr.length
      if (nameArr.length >= 2) {
        let obj = state[nameArr[0]]
        for (let i = 1; i < len - 1; i++) {
          obj = obj[nameArr[i]]
        }
        obj[nameArr[len - 1]] = data.data
        name = nameArr[0]
      } else {
        // 单层级变量，在state就是一个普通变量的情况
        state[data.name] = data.data
        name = data.name
      }
      if (cacheNames.includes(name)) {
        uni.setStorageSync(name, state[name])
      }
    }
  },
  actions: {
    initCache({ commit }) {
      commit("INIT_CACHE")
    }
  }
}
